<template>
  <px-dialog v-model="visible" title="新增题目" width="80%" fullscreen @close="cancel">
    <div v-loading="loading" class="content">
      <px-form ref="formRef" :model="subjectData" label-width="100px" :rules="rules">
        <px-form-item label="题目分类" prop="category">
          <px-select v-model="subjectData.category" style="width: 300px" placeholder="请选择题目类型" clearable>
            <px-option v-for="item in categoryList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="题目类型" prop="type">
          <px-select v-model="subjectData.type" style="width: 300px" placeholder="请选择题目类型" clearable @change="changeType">
            <px-option v-for="item in subjectTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="分值" prop="score">
          <px-input-number v-model="subjectData.score" placeholder="请输入分值" style="width: 300px" />
        </px-form-item>
        <px-form-item label="题目名称" prop="title">
          <WangEditor ref="subjectTitleRef" />
        </px-form-item>

        <div v-if="subjectData.type !== 'T'">
          <div>选项列表</div>
          <div class="option-content">
            <px-form-item v-for="(item, index) in subjectData.optionList" :key="item" :label="order[index]" :prop="item.value">
              <WangEditor :ref="el => setRef(el, index)" />
              <px-tooltip content="新增" placement="top">
                <px-button link icon="Plus" type="primary" style="margin-left: 16px" @click="addOption(index)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button link icon="Delete" type="danger" @click="deleteOption(index)" />
              </px-tooltip>
            </px-form-item>
          </div>
        </div>
        <px-form-item label="参考答案" :prop="subjectData.referenceAnswer">
          <div v-if="subjectData.type === 'S'">
            <px-radio-group v-model="subjectData.referenceAnswer">
              <px-radio v-for="(item, index) in subjectData.optionList" :key="item" :label="order[index]">{{ order[index] }}</px-radio>
            </px-radio-group>
          </div>
          <div v-if="subjectData.type === 'M'">
            <px-checkbox-group v-model="subjectData.mAnswer">
              <px-checkbox v-for="(item, index) in subjectData.optionList" :key="item" :label="order[index]" />
              {{ order[index] }}
            </px-checkbox-group>
          </div>
          <div v-if="subjectData.type === 'T'">
            <px-radio-group v-model="subjectData.referenceAnswer">
              <px-radio :label="'正确'">正确</px-radio>
              <px-radio :label="'错误'">错误</px-radio>
            </px-radio-group>
          </div>
        </px-form-item>
      </px-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancel">取消</px-button>
        <px-button type="primary" @click="save">保存</px-button>
      </span>
    </template>
  </px-dialog>
</template>
<script setup>
import { computed, ref, reactive, toRefs, onMounted, nextTick } from "vue";
import WangEditor from "@/views/all/knowledge/examManage/component/wangEditor.vue";
import { saveQuestionAPI, getQuestionListAPI } from "@/api/knowledge/examManage";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  categoryList: {
    type: Array,
    default: () => []
  }
});

const emits = defineEmits(["update:visible", "save"]);

const visible = computed({
  get: () => props.visible,
  set: val => emits("update:visible", val)
});

const formRef = ref(null);
const order = Array(26)
  .fill("")
  .map((i, index) => String.fromCharCode(65 + index));
const subjectTitleRef = ref();

const rules = computed(() => ({
  category: [{ required: true, message: "题目分类不能为空", trigger: "change" }],
  type: [{ required: true, message: "题目类型不能为空", trigger: "change" }],
  score: [{ required: true, message: "分值不能为空", trigger: "blur" }]
}));

const state = reactive({
  subjectTypeList: [
    {
      name: "单选题",
      value: "S"
    },
    {
      name: "多选题",
      value: "M"
    },
    {
      name: "判断题",
      value: "T"
    }
  ],
  subjectData: {
    category: "",
    type: "",
    score: null,
    subjectTitle: "",
    optionList: [
      {
        value: "",
        content: ""
      }
    ],
    referenceAnswer: "",
    mAnswer: []
  }
});
const { subjectTypeList, subjectData } = toRefs(state);

let editorRefs = {};
const setRef = (el, index) => {
  if (el) {
    editorRefs[`optionEditorRef${index}`] = el;
  }
};

// 新增选项
const addOption = index => {
  state.subjectData.optionList.push({
    value: "",
    content: ""
  });
};

// 删除选项
const deleteOption = index => {
  state.subjectData.optionList.splice(index, 1);
};

const cancel = () => {
  emits("update:visible", false);
};

const changeType = val => {
  state.subjectData.type = val;
  if (val === "S" || val === "M") {
    for (let i = 1; i < 4; i++) {
      state.subjectData.optionList.push({
        value: order[i],
        content: ""
      });
    }
  }
};

const getExamList = async () => {
  try {
    state.loading = true;
    const params = {
      categoryId: state.subjectData.category,
      questionType: state.subjectData.type,
      questionName: subjectTitleRef.value.valueHtml,
      size: 20,
      current: 1
    };
    const res = await getQuestionListAPI(params);
    emits("update:visible", false);
    emits("save", res.records);
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

const save = () => {
  formRef.value?.validate(async validate => {
    if (validate) {
      if (subjectTitleRef.value.valueHtml === undefined || subjectTitleRef.value.valueHtml === "") {
        PxMessage.error("题目名称不能为空");
        return;
      }
      let optionList = state.subjectData.optionList.map((_, index) => {
        const { htmlVal, textVal } = editorRefs[`optionEditorRef${index}`].getContent();
        return {
          optionName: order[index],
          optionContent: htmlVal,
          optionText: textVal,
          sort: index
        };
      });
      let v = optionList.filter(item => item.optionText === undefined || item.optionText === "");
      if (v.length > 0 && state.subjectData.type !== "T") {
        PxMessage.error("选项内容不能为空");
        return;
      }
      let a = state.subjectData.type === "M" ? state.subjectData.mAnswer.toString() : state.subjectData.referenceAnswer;
      if (a === "") {
        PxMessage.error("参考答案不能为空");
        return;
      }
      const params = {
        questionId: null,
        categoryId: state.subjectData.category,
        questionName: subjectTitleRef.value.valueHtml,
        type: state.subjectData.type,
        score: state.subjectData.score,
        answer: state.subjectData.type === "M" ? state.subjectData.mAnswer.toString() : state.subjectData.referenceAnswer,
        questionOptions: optionList
      };
      try {
        state.loading = true;
        await saveQuestionAPI(params);
        getExamList();
      } catch (error) {
        console.log(error);
      } finally {
        state.loading = false;
      }
    }
  });
};
</script>
<style lang="scss" scoped>
:deep(.px-dialog__body) {
  overflow-y: auto !important;
}

.content {
  height: calc(100vh - 156px);
  overflow-y: auto;
}
</style>
